﻿myApp.controller("PropertiesController", function ($scope, $http, $modal, ngTableParams, $routeParams, $filter, authService, $location, $window) {
    document.title = "Penang Realty BUY OR RENT WITH US 世界地產 Property Sale/Rent";
    $scope.$emit('newPageLoaded', { 'title': 'Penang Realty BUY OR RENT WITH US 世界地產 Property Sale/Rent', 'description': 'Free search for properties you want.' });

    $scope.data.searchData = [];
    $scope.internaluser = false;
    
    if ($scope.authentication.userType !== "Valid User" && $scope.authentication.userType !== "") $scope.internaluser = true;

    console.log($scope.authentication.userType);

    function pageInit() {
        
        /*
        $http.get('api/Property/GetState')
             .success(function (data) {
                 linkRouteParam($routeParams);
                 $scope.states = data;
                 
                 $scope.search();
            }
            )
        */
    }
    $scope.query = function test() {
        
        linkRouteParam($routeParams);
        $scope.search();
    }

    function linkRouteParam(param) {
        //$scope.property.saleType = $scope.property.transact + $scope.property.Type;

        var p1 = String(param.id);
        $scope.Transact = p1;

        var p2 = String(param.id2);
        charTransact = p1.substr(0, 1);
        charType = p2.substr(0, 1);
        $scope.Type = p2;

        if (charTransact.toUpperCase() == 'R') {
            $scope.property.transact = 'R'
        } else {
            $scope.property.transact = 'S'
        }

        // TransactionType
        if (charType.toUpperCase() == 'C') {
            $scope.property.Type = 'C'
        }
        else if (charType.toUpperCase() == 'I') {
            $scope.property.Type = 'I'
        }
        else if (charType.toUpperCase() == 'L') {
            $scope.property.Type = 'L'
        }
        else {
            $scope.property.Type = 'R'
        }

    }

    $scope.changeState = function () {
        if ($scope.property.StateId) {
            $http.get('api/Property/GetLocation/' + $scope.property.StateId)
           .success(function (data) {

               $scope.locations = data;
           }
           )
        }
    }

    $scope.tableParams = new ngTableParams({
        page: 1,            // show first page
        count: 50,           // count per page
        filter: {
            //Project: ''       // initial filter
        }

    }, {
        total: $scope.data.searchData.length, // length of data
        getData: function ($defer, params) {
            var orderedProperty = params.filter() ? $filter('filter')($scope.data.searchData, params.filter()) : $scope.data.searchData;
            // use build-in angular filter
            orderedProperty = params.sorting() ? $filter('orderBy')(orderedProperty, params.orderBy()) : orderedProperty;
            params.total(orderedProperty.length); // set total for recalc pagination
            $defer.resolve(orderedProperty.slice((params.page() - 1) * params.count(), params.page() * params.count()));         
        }
    })

    $scope.search = function () {
        $scope.loader.loading = true;
        validateSearch();

        if ($scope.tableParams !== undefined) $scope.tableParams.reload();

        if ($scope.property.transact == "S") url = 'api/PropertySearch/GetSaleProperty';
        else url = 'api/PropertySearch/GetRentProperty';
        //console.log("$scope.property : ");
        //location.hash = "#notification";
        var element_to_scroll_to = document.getElementById('notification');
        element_to_scroll_to.scrollIntoView();

        $http.post(url, $scope.property)
             .success(function (result) {
                 console.log(result);
                 $scope.loader.loading = false;
                 $scope.data.searchData = result;
                 window.prerenderReady = true;
                               
             })
             .error(function (result) {
                 console.log("Error");
                 console.log(result);
                 $scope.loader.loading = false;
                 window.prerenderReady = true;

             }
         )        
    }

    $scope.$watch('data.searchData', function (newValue, oldValue) {
           if ($scope.tableParams) $scope.tableParams.reload();
    });

    $scope.go = function (key, value) {
        console.log($scope.property.transact);
        value['transact'] = $scope.property.transact;
        var jsonObj = JSON.stringify(value);
        sessionStorage.setItem(key, jsonObj);
    }

    $scope.clearEntry = function () {
        $scope.property.Type = "";
        $scope.property.StateId = "";
        $scope.property.transact = "";
        $scope.property.location = "";
        $scope.property.project = "";
        $scope.property.priceMin = 0;
        $scope.property.priceMax = 99999999;
        $scope.data.searchData = [];
    }

    validateSearch = function ()
    {

        if (typeof ($scope.property["priceMax"]) !== "undefined")
            if ($scope.property.priceMax == "null")
                $scope.property.priceMax = null;
         
        $scope.property.saleType = $scope.property.transact + $scope.property.Type;
    }
    pageInit();

   
})


